package controllers;

import play.*;
import play.data.validation.CheckWith;
import play.data.validation.Required;
import play.data.validation.Valid;
import play.mvc.*;
import utils.Constants;
import utils.Secure;

import java.util.*;

import org.apache.commons.lang.StringUtils;

import models.*;

public class Stories extends Application {
    public static void list(Long userId) {
		List<Story> stories = Story.find("user.id = ? order by id desc",userId).fetch();
        render(stories);
    }
	/**
	 * 创建或编辑对象
	 * @param id
	 */
	public static void edit(Long id){
		Story story = null;
		if(id!=null){
			story = Story.findById(id);
			Long userId = Long.parseLong(session.get(Constants.USER_ID_IN_SESSION));
			if(story.user.id != userId){
				forbidden();
			}
		}
		render(story);
	}
	
	public static void save(Story story){
		if(validation.hasErrors()){
			validation.keep();
			params.flash();
			edit(null);
		}
		story.user = User.find("byUsername", session.get(Constants.USERNAME_IN_SESSION)).first();
		if(story.id == null){
			story.createDate = new Date();
			story.lastUpdateDate = story.createDate;
			story.lastUpdateContent = story.description;
		}
		story.save();
		list(story.user.id);
	}
	public static void view(Long id){
		Story story = Story.findById(id);
		render(story);
	}
	/**
	 * 删除故事
	 * @param id
	 */
	public static void delete(Long id){
		Story story = Story.findById(id);
		Long userId = Long.parseLong(session.get(Constants.USER_ID_IN_SESSION));
		if(story.user.id == userId){
			story.delete();
		}else{
			forbidden();
		}
		Stories.list(userId);
	}
	/**
	 * 添加到收藏/关注
	 * @param id
	 * @param userId
	 */
	public static void addToFavorite(@Required Long storyId){
		String result = Constants.AJAX_SUCCESS;
		try{
			Long userId = Long.parseLong(session.get(Constants.USER_ID_IN_SESSION));
			FavoriteStory favoriteStory = new FavoriteStory(storyId,userId);
			favoriteStory.save();
		}catch (Exception e) {
			Logger.error("AddToFavorite Error", new Object[]{e.getStackTrace()});
			result = Constants.AJAX_FAILED;
		}
		renderJSON(result);
	}
	/**
	 * 取消收藏/关注
	 * @param storyId
	 * @param userId
	 */
	@Secure
	public static void removeFavorite(@Required Long storyId){
		String result = Constants.AJAX_SUCCESS;
		try{
			Long userId = Long.parseLong(session.get(Constants.USER_ID_IN_SESSION));
			FavoriteStory favoriteStory = FavoriteStory.find("story.id = ? and user.id = ?", storyId,userId).first();
			favoriteStory.delete();
		}catch(Exception e){
			Logger.error("removeFavorite Error", new Object[]{e.getStackTrace()});
			result = Constants.AJAX_FAILED;
		}
		renderJSON(result);
	}
	/**
	 * 推荐/发现 可能感兴趣的故事
	 * TODO
	 */
	public static void recommend(){
		List<Story> stories = Story.findAll();
		render(stories);
	}
	/**
	 * 列出感兴趣的故事
	 */
	public static void listFollows(){
		List<Story> stories = Story.findAll();
		render(stories);
	}
}